// go语言范围(Range) -- 迭代数组、切片、通道、集合
package main

import "fmt"

/**
 * range格式
 * for key, value := range oldMap {
 *   newMap[key] = value
 * }
 * 简写：
 * 1.for key := range oldMap
 * 2.for _, value := range oldMap
 */
var pow = []int {1, 2, 4, 8, 16, 32, 64, 128}
func t1() {
	for i, v := range pow {
		fmt.Printf("2**%d = %d\n", i, v)
	}
}

func t2() {
	map1 := make(map[int] float32)
	map1[1] = 1.0
	map1[2] = 2.0
	map1[3] = 3.0
	map1[4] = 4.0

	// 读取key和value
	for key, value := range map1 {
		fmt.Printf("key is: %d - value is: %f\n", key, value)
	}
	// 读取key
	for key := range map1 {
		fmt.Printf("key is: %d", key)
	}
	// 读取value
	for _, value := range map1 {
		fmt.Printf("value is: %f\n", value)
	}
}

func t3() {
	nums := []int {2, 3, 4}
	sum := 0
	for _, num := range nums {
		sum += num
	}
	fmt.Println("sum: ", sum)
	for i, num := range nums {
		if num == 3 {
			fmt.Println("index: ", i)
		}
	}

	kvs := map[string] string {"a": "apple", "b": "banana"}
	for k, v := range kvs {
		fmt.Printf("%s -> %s\n", k, v)
	}
	for i, c := range "go" {
		fmt.Println(i, c)
	}
}

func main() {
	t1()
	t2()
	t3()
}